package com.tree.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tree.backend.common.Result;
import com.tree.backend.entity.Device;
import com.tree.backend.entity.OptimizationTask;
import com.tree.backend.service.IDeviceService;
import com.tree.backend.service.IOptimizationTaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Collectors;

/**
 * <p>
 * 信号优化任务表 前端控制器
 * </p>
 *
 * @author tree
 * @since 2025-10-24
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/optimization-task")
public class OptimizationTaskController {

    private final IDeviceService deviceService;
    private final IOptimizationTaskService optimizationTaskService;

    /**
     * 获取任务列表（分页+搜索）
     */
    @GetMapping("/list")
    public Result<IPage<OptimizationTask>> getTaskList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String taskName,
            @RequestParam(required = false) String taskType,
            @RequestParam(required = false) Integer status) {

        Page<OptimizationTask> pageParam = new Page<>(page, size);
        QueryWrapper<OptimizationTask> queryWrapper = new QueryWrapper<>();

        if (StringUtils.hasText(taskName)) {
            queryWrapper.like("task_name", taskName);
        }
        if (StringUtils.hasText(taskType)) {
            queryWrapper.eq("task_type", taskType);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }

        queryWrapper.orderByDesc("create_time");
        IPage<OptimizationTask> taskPage = optimizationTaskService.page(pageParam, queryWrapper);
        // 获取设备名称
        List<Device> deviceList = deviceService.list();
        taskPage.getRecords().forEach(task -> {
            Device device = deviceList.stream().filter(d -> d.getId().equals(task.getDeviceId())).findFirst().orElse(null);
            if (device != null) task.setDeviceName(device.getDeviceName());
        });
        return Result.success(taskPage);
    }

    /**
     * 获取任务详情
     */
    @GetMapping("/{id}")
    public Result<OptimizationTask> getTaskDetail(@PathVariable Integer id) {
        OptimizationTask task = optimizationTaskService.getById(id);
        if (task == null) {
            return Result.error("任务不存在");
        }
        return Result.success(task);
    }

    /**
     * 添加任务
     */
    @PostMapping
    public Result<String> addTask(@RequestBody OptimizationTask task) {
        boolean success = optimizationTaskService.save(task);
        return success ? Result.success("添加任务成功") : Result.error("添加任务失败");
    }

    /**
     * 更新任务
     */
    @PutMapping("/{id}")
    public Result<String> updateTask(@PathVariable Integer id, @RequestBody OptimizationTask task) {
        task.setId(id);
        boolean success = optimizationTaskService.updateById(task);
        return success ? Result.success("更新任务成功") : Result.error("更新任务失败");
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteTask(@PathVariable Integer id) {
        boolean success = optimizationTaskService.removeById(id);
        return success ? Result.success("删除任务成功") : Result.error("删除任务失败");
    }

    /**
     * 批量删除任务
     */
    @DeleteMapping("/batch")
    public Result<String> batchDeleteTasks(@RequestParam String ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的任务");
        }
        
        // 将逗号分隔的字符串转换为整数列表
        List<Integer> idList = Arrays.stream(ids.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        
        boolean success = optimizationTaskService.removeByIds(idList);
        return success ? Result.success("批量删除任务成功") : Result.error("批量删除任务失败");
    }

    /**
     * 执行任务
     */
    @PostMapping("/{id}/execute")
    public Result<String> executeTask(@PathVariable Integer id) {
        OptimizationTask task = optimizationTaskService.getById(id);
        if (task == null) {
            return Result.error("任务不存在");
        }

        // 模拟任务执行逻辑
        task.setStatus(1); // 执行中
        task.setExecuteTime(LocalDateTime.now()); // 设置执行时间
        optimizationTaskService.updateById(task);

        // 模拟执行过程
        try {
            Thread.sleep(2000); // 模拟执行耗时
            task.setStatus(2); // 已完成
            optimizationTaskService.updateById(task);
            return Result.success("任务执行成功");
        } catch (InterruptedException e) {
            task.setStatus(3); // 失败
            optimizationTaskService.updateById(task);
            return Result.error("任务执行失败");
        }
    }

    /**
     * 批量执行任务
     */
    @PostMapping("/batch-execute")
    public Result<String> batchExecuteTasks(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要执行的任务");
        }

        // 批量更新任务状态为执行中
        List<OptimizationTask> tasks = optimizationTaskService.listByIds(ids);
        LocalDateTime now = LocalDateTime.now();
        for (OptimizationTask task : tasks) {
            task.setStatus(1);
            task.setExecuteTime(now); // 设置执行时间
        }
        optimizationTaskService.updateBatchById(tasks);

        // 模拟批量执行
        try {
            Thread.sleep(3000); // 模拟批量执行耗时
            for (OptimizationTask task : tasks) {
                task.setStatus(2); // 已完成
            }
            optimizationTaskService.updateBatchById(tasks);
            return Result.success("批量执行任务成功");
        } catch (InterruptedException e) {
            for (OptimizationTask task : tasks) {
                task.setStatus(3); // 失败
            }
            optimizationTaskService.updateBatchById(tasks);
            return Result.error("批量执行任务失败");
        }
    }

    /**
     * 获取任务统计信息
     */
    @GetMapping("/stats")
    public Result<Object> getTaskStats() {
        // 统计各种状态的任务数量
        QueryWrapper<OptimizationTask> pendingWrapper = new QueryWrapper<>();
        pendingWrapper.eq("status", 0);
        long pendingCount = optimizationTaskService.count(pendingWrapper);

        QueryWrapper<OptimizationTask> runningWrapper = new QueryWrapper<>();
        runningWrapper.eq("status", 1);
        long runningCount = optimizationTaskService.count(runningWrapper);

        QueryWrapper<OptimizationTask> completedWrapper = new QueryWrapper<>();
        completedWrapper.eq("status", 2);
        long completedCount = optimizationTaskService.count(completedWrapper);

        QueryWrapper<OptimizationTask> failedWrapper = new QueryWrapper<>();
        failedWrapper.eq("status", 3);
        long failedCount = optimizationTaskService.count(failedWrapper);

        // 统计任务总数
        long totalCount = optimizationTaskService.count();

        // 返回统计信息
        return Result.success(new Object() {
            public final long total = totalCount;
            public final long pending = pendingCount;
            public final long running = runningCount;
            public final long completed = completedCount;
            public final long failed = failedCount;
        });
    }
}